package com.rc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rc.entity.GenDatasource;
import com.rc.entity.GenTable;
import com.rc.entity.gencode.GenDataSource;
import com.rc.service.GenDatasourceService;
import com.rc.entity.web.PageParam;
import com.rc.entity.web.Result;
import com.rc.util.DbUtils;
import com.rc.util.GenUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(tags="dataSource接口")
@RequestMapping("/genDatasource")
public class GenDatasourceController {

    @Autowired
    private GenDatasourceService genDatasourceService;

    /**
    * 根据id获取对象
    * @param id
    * @return
    */
    @GetMapping("/{id}")
    public GenDatasource getById(@PathVariable Long id) {
        return genDatasourceService.getById(id);
    }

    /**
    * 分页查询
    * @param pageParam
    * @return
    */
    @PostMapping("/queryByPage")
    public Result queryUserByPage(PageParam pageParam){
        QueryWrapper<GenDatasource> genDatasourceQueryWrapper = new QueryWrapper<>();
        Map<String, String> queryMap = pageParam.getQueryMap();
        if (StringUtils.isNotBlank(queryMap.get("id"))){
            genDatasourceQueryWrapper.like("id",queryMap.get("id"));
        }
        Page<GenDatasource> genDatasourcePage = genDatasourceService.page(new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize()), genDatasourceQueryWrapper);
        return Result.SUCCESS(genDatasourcePage);
    }

    @GetMapping("/test")
    public Result<String> test(@RequestParam("id") String id) {
        try {
            GenDatasource entity = genDatasourceService.getById(id);
            DbUtils.getConnection(new GenDataSource(entity));
            return Result.SUCCESS("测试连接成功");
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
            return Result.ERROR("连接失败，请检查配置信息");
        }
    }

    /**
     * 根据数据源ID，获取全部数据表
     *
     * @param id 数据源ID
     */
    @GetMapping("table/list")
    public Result tableList(@RequestParam("id") String id) {
        try {
            // 获取数据源
            GenDataSource datasource = genDatasourceService.get(id);
            // 根据数据源，获取全部数据表
            List<GenTable> tableList = GenUtils.getTableList(datasource);
            return Result.SUCCESS(tableList);
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
            return Result.ERROR("数据源配置错误，请检查数据源配置！");
        }
    }
}
